﻿using BLL;
using CommonUtility;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication
{
    public partial class Login : System.Web.UI.Page
    {
        protected string target;

        protected void Page_Load(object sender, EventArgs e)
        {
            target = Request.Url.AbsoluteUri;
            target = target.IndexOf("?") == -1 ? "" : Server.UrlEncode(target.Substring(target.IndexOf("?") + 1));
            if (!string.IsNullOrEmpty(target))
            {
                target = Server.HtmlDecode(target);
            }

            string ajax = Common.ToString(Request["ajax"]);
            if (ajax == "ajax")
            {
                string name = Common.ConvertSql(Common.ToString(Request["name"]));
                string pwd = Common.ToString(Request["pwd"]);
                Response.Write(DoLogin(name, pwd));
                Response.End();
            }
        }

        protected string DoLogin(string _name, string _pwd)
        {
            string result = string.Empty;
            UserInfo user = bllUser.GetUser(_name);
            if (ValidateUserAccount(_name, _pwd))
            {
                if (user.RID != 0)
                {
                    Session["User"] = user;
                    Response.Cookies["app-user"].Value = user.UserID;
                    Response.Cookies["app-user"].Expires = DateTime.Now.AddDays(30);
                    try
                    {
                        bllLog.AddLog("", "Login", Request.UserHostAddress + "<br/>" + Request.UserAgent, user.UserID);
                    }
                    catch (Exception ex)
                    {
                        Common.Application_Error_Server("Login-en.aspx.cs/VendorLogin() " + user.Name, ex);
                    }
                }
                else
                    result = "You do not have permission to use the system.";
            }
            else
                result = "Username or password is incorrect.";
            return result;
        }

        private bool ValidateUserAccount(string _name, string _pwd)
        {
            //防止sql注入
            _name = Common.ToString(_name); _pwd = Common.ToString(_pwd);
            int count = DAL.User.GetList(" UserId='" + _name + "' and pwd='" + _pwd + "'").ToList().Count;
            return count > 0 ? true : false;
        }
    }
}